"""
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License. 
"""
from logging import getLogger

from twisted.application.service import Service

from meercat.job.interfaces import IJob



log = getLogger('meercat.job.service')

class JobService(Service):
    
    _jobs = []
    
    def add(self,job):
        """ """
        job = IJob(job)
        
        self._jobs.append(job)
        
        log.debug('JobService: Adding a job: %s' % (str(job),))
        
        if self.running:
            job.start()
    
    def remove(self, job):
        job = IJob(job)
        
        log.debug('JobService: Removing a job: %s' % (str(job),))
        
        if job in self._jobs:
            self._jobs.remove(job)
            return job.stop()
    
    def startService(self):
        Service.startService(self)
        
        log.debug('JobService Starting')
        
        for job in self._jobs:
            log.debug('JobService: Starting %s' % (str(job),))
            job.start()
    
    def stopService(self):
        """Eventually need to make this so that when a job is stopped and it 
        returns a deferred (meaning it will take a while to stop), this 
        collects them and returns a new deferred that is triggered when all of 
        the outstanding jobs finish stopping """
        
        Service.stopService(self)
        
        log.debug('JobService: Stopping')
        
        for job in self._jobs:
            log.debug('JobService: Stopping: %s' % (str(job),))
            job.stop()
    
    def getJobs(self):
        return self._jobs
